package com.saver.view;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.DatePicker;

import com.saver.core.util.DateUtil;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by HeRGoS on 18/04/2015
 */
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    private static final String TAG = "DatePickerFragment";

    Button botonFecha;

    public void setBotonFecha(Button botonFecha) {
        this.botonFecha = botonFecha;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTimeInMillis(DateUtil.FORMATO_GENERAL.parse(botonFecha.getText().toString()).getTime());
        } catch (ParseException e) {
            Log.e(TAG, "error de parseo", e);
        }
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
        dialog.getDatePicker().setMaxDate(new Date().getTime());
        return dialog;
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, day);
        String fecha = DateUtil.FORMATO_GENERAL.format(new Date(cal.getTimeInMillis()));
        botonFecha.setText(fecha);
    }
}
